package com.ph.controller;

import com.ph.shopping.facade.pay.utils.PayecoConfig;
import com.ph.shopping.facade.pay.utils.PayecoUtils;
import com.ph.shopping.facade.pay.vo.PayVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @项目：phshopping-api-pay
 * @描述：支付controller
 * @作者： 张霞
 * @创建时间： 14:29 2017/3/23
 * @Copyright @2017 by zhangxia
 */
@Controller
@RequestMapping("pay")
public class PayecoController {
    // 创建公共日志
    protected Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 易联支付接口
     * @param request
     * @param payVo 支付传入参数Vo
     * @return
     * @author Mr.Chang
     */
    @RequestMapping(value = "/payeco", method = RequestMethod.POST)
    public String payecoPay(HttpServletRequest request, HttpServletResponse response, @ModelAttribute PayVo payVo, Map<String, Object> map) {
        logger.info("******************************开始跳转支付接口*********************************");
        String returnUrl = "error/pay/payeco/error";

        //参数校验
        if (StringUtils.isEmpty(payVo.getAmount()) || StringUtils.isEmpty(payVo.getOrderNum())) {
            map.put("msg", "参数解析错误!");
            return returnUrl;
        }

        try {
            //获得MD5加密验签
            String mac = PayecoUtils.getMac(payVo.getAmount(), payVo.getOrderNum());
            logger.info("生成的的mac值：" + mac);
            //组装支付报文
            String requestText = PayecoUtils.encryptMiWen(mac, payVo.getAmount(), request.getLocalAddr(), payVo.getDescription(), payVo.getOrderNum());

            //保存MD5加密验签
//            payService.updateOrderMD5Sign(payVo.getOrderNum(), mac);

            logger.info("报文发送内容:" + requestText);
            map.put("requestText", requestText);
            map.put("urlReaction", PayecoConfig.payecoUrl);
            returnUrl = "pay/payeco";
        } catch (Exception e) {
            logger.error("跳转支付页面异常：" + e);
            returnUrl = "error/pay/payeco/error";
            map.put("msg", "组装报文异常");
        }
        logger.info("******************************结束跳转支付接口*********************************");
        return returnUrl;
    }

}
